package bavaria.hightech.timer;

import java.awt.Graphics;
import java.util.TimerTask;
import java.util.Timer;
import java.util.Calendar;
import java.util.Date;
import java.text.DateFormat;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Clock extends JFrame {
    private static final int TICK_PERIOD = 100;
    private Timer ticker;
    private JPanel panel;
    private Calendar time;

    private class TickerTask extends TimerTask {
        public void run() {
            panel.repaint();
        }
    }

    private class ClockDisplay extends JPanel {
        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Date date = time.getTime();
            DateFormat dateFormatter = DateFormat.getTimeInstance();
            g.setFont(new Font(null,Font.PLAIN,20));
            g.drawString(dateFormatter.format(date), 20, 50);
            dateFormatter = DateFormat.getDateInstance();
            g.drawString(dateFormatter.format(date), 10, 30);
        }
    }


    public Clock(Calendar time, Timer timer) {
        panel = new ClockDisplay();
        add("Center", panel);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(100, 100);
        setVisible(true);
        this.time = time;
        ticker = timer;
        start();
    }

    public void start() {
//        ticker = new Timer(true); //as daemon
        ticker.scheduleAtFixedRate(new TickerTask(), 0, TICK_PERIOD);
    }
}